package com.hbpu.encap.socket.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.print("服务端在监听9999端口，等待连接");

        // 启动一个动画线程，用于在等待连接时显示加载动画
        Thread animationThread = new Thread(() -> {
            char[] animationChars = new char[]{'\\', '/', '-'};
            int index = 0;
            while (!Thread.currentThread().isInterrupted()) {
                // \r 回到行首，输出带下划线的动画
                System.out.print("\r等待连接 " + animationChars[index % animationChars.length] + "_");
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    // 线程被中断时退出循环
                    Thread.currentThread().interrupt();
                }
                index++;
            }
        });
        animationThread.start();

        // 阻塞等待客户端连接
        Socket accept = serverSocket.accept();

        // 连接成功后，中断动画线程
        animationThread.interrupt();

        System.out.println("\n连接成功！" + accept.getClass());
        InputStream inputStream = accept.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        bufferedReader.close();
        serverSocket.close();
    }
}
